extends IEventActuator


class_name PropertySetter
"""
设置属性值
"""


signal event_value_will_changed(setter: PropertySetter, target: Object, key: String, value: Variant)


## 需要设置的属性,支持.分隔子属性
@export var property: String = ""

@export_category("Option")
## 是否需要使用set_deferred执行
@export var is_deferred: bool = false
## 是否在下一次执行时允许重置
@export var is_resetable: bool = false
@export_category("")


var is_stored: bool = false
var stored_value: Variant = null


var cached_w: Object = null
var cached_p: String = ""


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "property": func(): return property.length() > 0,
    }, super.__check_exports())

func __get_update_value(w: Object, p: String) -> Variant:
    return null

func __get_wrapper_and_property() -> bool:
    return false

func __set_value(w: Object, p: String, value: Variant) -> void:
    event_value_will_changed.emit(self, w, property, value)
    if is_deferred:
        w.call_deferred("set", p, value)
    else:
        w.set(p, value)

func __execute_value(w: Object, p: String) -> void:
    var new_value: Variant = __get_update_value(w, p)
    if new_value != null:
        __set_value(w, p, new_value)

func __execute_stored(w: Object, p: String) -> void:
    if is_stored:
        __set_value(w, p, stored_value)
    else:
        stored_value = w.get(p)
        __execute_value(w, p)
    is_stored = not is_stored

func execute() -> void:
    if not IComponent.is_available(self):
        return
    if __get_wrapper_and_property() and cached_w:
        if is_resetable:
            __execute_stored(cached_w, cached_p)
        else:
            __execute_value(cached_w, cached_p)
    else:
        push_warning("%s get property failed:%s" % [self, property])
